package com.eagle.web.method.support;

import com.eagle.web.http.converter.properties.MappingProperties2HttpMessageConverter;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

public class PropertiesHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		return Properties.class.equals(returnType.getMethod().getReturnType());
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
		Properties properties = (Properties)  returnValue;
		MappingProperties2HttpMessageConverter converter = new MappingProperties2HttpMessageConverter();

		ServletWebRequest servletRequest = (ServletWebRequest) webRequest;
		HttpServletRequest request = servletRequest.getRequest();
		String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
		MediaType mediaType = (StringUtils.hasLength(header) ? MediaType.parseMediaType(header) : null);

		HttpServletResponse response = servletRequest.getResponse();
		HttpOutputMessage message =new ServletServerHttpResponse(response);

		converter.write(properties,mediaType,message);

		mavContainer.setRequestHandled(true);
	}
}
